//
//  RegisterViewController.swift
//  MiU
//
//  Created by linhan on 15/11/9.
//  Copyright © 2015年 MiU. All rights reserved.
//

import Foundation
import UIKit
class SWRegisterViewController: SWBaseViewController,SWAPIComponent,UITextFieldDelegate
{
    var verifyCode:String = ""
    var phone:String = ""
    var ssoTicket:String = ""
    
    
    private var _intervalID:String = ""
    private var _smsSendTime:Double = 0
    private var _registered:Bool = false
    
    lazy private var _getCodeBtn:UIButton = UIButton(type:.system)
    
    lazy private var _topView:UIView = UIView()
    lazy private var _telTextField:ImageTextField = ImageTextField()
    lazy private var _codeTextField:ImageTextField = ImageTextField()
    lazy private var _passwordTextField:ImageTextField = ImageTextField()
    
    private var _regBtn:UIButton = UIButton(type:.system)
    
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        setup()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if navigationController == nil
        {
            clearInterval(_intervalID)
        }
    }
    
    deinit
    {
        trace("DEINIT RegisterViewController")
    }
    
    //是否处于冷却中
    private var inWaiting:Bool
    {
        return (SW.Config.GetVerifyCodeCDTime - ((NSDate().timeIntervalSince1970 - _smsSendTime))) > 0
    }
    
    //以注册为目的
    private var _registerPurpose:Bool{
        return ssoTicket.length == 0
    }
    
    //MARK ============================================================================================
    //==============================            Public Method           ===============================
    //=================================================================================================
    
    
    private func setup()
    {
        title = _registerPurpose ? "注册" : "绑定手机号"
        view.backgroundColor = UIColor.white
        
        
        let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
        view.addGestureRecognizer(tapGesture)
        
        let TextFieldWidth:CGFloat = view.width * 0.733
        let TextFieldHeight:CGFloat = 50
        let TextFieldLeftMargin:CGFloat = (view.width - TextFieldWidth) * 0.5
        let PlaceholderColor:UIColor = UIColor(hex: "0xababab")
        let InputColor:UIColor = UIColor.darkGray
        let TextFieldBorderColor:UIColor = UIColor(hex: 0xd0d0d0)
        
        //输入时整个topview上移
        _topView.frame = CGRectMake(0, navigationBarBottom + 44.0, view.width, 0)
        view.addSubview(_topView)
        
        //手机输入框
        _telTextField.frame = CGRectMake(TextFieldLeftMargin, 0, TextFieldWidth, TextFieldHeight)
        _telTextField.textInset = UIEdgeInsetsMake(0, 18, 0, 18)
        _telTextField.font = UIFont.systemFont(ofSize:14)
        _telTextField.textAlignment = .left
        _telTextField.keyboardType = .phonePad
        _telTextField.clearButtonMode = .whileEditing
        _telTextField.delegate = self
        _telTextField.attributedPlaceholder = NSMutableAttributedString(string: "请输入手机号码", attributes: [NSForegroundColorAttributeName:PlaceholderColor])
        _telTextField.textColor = InputColor
        _telTextField.layer.borderColor = TextFieldBorderColor.cgColor
        _telTextField.layer.borderWidth = 1
        _telTextField.layer.cornerRadius = 4
        _telTextField.layer.masksToBounds = true
        _topView.addSubview(_telTextField)
        
        //验证码
        let codeView = UIView()
        codeView.layer.borderColor = TextFieldBorderColor.cgColor
        codeView.layer.borderWidth = 1
        codeView.layer.cornerRadius = 4
        codeView.layer.masksToBounds = true
        codeView.frame = CGRectMake(TextFieldLeftMargin, _telTextField.bottom + 25, TextFieldWidth, TextFieldHeight)
        _topView.addSubview(codeView)
        
        let CodeButtonWidth:CGFloat = 100
        let CodeButtonHeight:CGFloat = TextFieldHeight
        _getCodeBtn.frame = CGRectMake(codeView.width - CodeButtonWidth, 0, CodeButtonWidth, CodeButtonHeight)
        _getCodeBtn.titleLabel?.font = UIFont.systemFont(ofSize:14)
        _getCodeBtn.setTitleColor(UIColor(hex:0xf4c4c1), for: .normal)
        _getCodeBtn.addTarget(self, action: #selector(getCodeBtnTapped), for: .touchUpInside)
        getCodeButtonEnabled = true
        codeView.addSubview(_getCodeBtn)
        
        let sepaLine:UIView = UIView()
        sepaLine.backgroundColor = UIColor(hex: 0xd0d0d0)
        sepaLine.frame = CGRectMake(_getCodeBtn.x, 8, 1, codeView.height - 16)
        codeView.addSubview(sepaLine)
        
        _codeTextField.frame = CGRectMake(0, 0, _getCodeBtn.x, TextFieldHeight)
        _codeTextField.textInset = UIEdgeInsetsMake(0, 19, 0, 0)
        _codeTextField.font = UIFont.systemFont(ofSize:14)
        _codeTextField.keyboardType = .phonePad
        _codeTextField.delegate = self
        _codeTextField.attributedPlaceholder = NSMutableAttributedString(string: "输入验证码", attributes: [NSForegroundColorAttributeName:PlaceholderColor])
        _codeTextField.textColor = InputColor
        codeView.addSubview(_codeTextField)
        
        //密码
        _passwordTextField.frame = CGRectMake(TextFieldLeftMargin, codeView.bottom + 25, TextFieldWidth, TextFieldHeight)
        _passwordTextField.textInset = UIEdgeInsetsMake(0, 19, 0, 19)
        _passwordTextField.font = UIFont.systemFont(ofSize:14)
        _passwordTextField.textColor = InputColor
        _passwordTextField.isSecureTextEntry = true
        _passwordTextField.clearButtonMode = .whileEditing
        _passwordTextField.delegate = self
        _passwordTextField.layer.borderColor = TextFieldBorderColor.cgColor
        _passwordTextField.layer.borderWidth = 1
        _passwordTextField.layer.cornerRadius = 4
        _passwordTextField.layer.masksToBounds = true
        _passwordTextField.attributedPlaceholder = NSMutableAttributedString(string: "输入密码", attributes: [NSForegroundColorAttributeName:PlaceholderColor])
        _topView.addSubview(_passwordTextField)
        
        //注册
        let label:String = _registerPurpose ? "注册" : "绑定"
        _regBtn.setTitleColor(UIColor.white, for: .normal)
        _regBtn.titleLabel?.font = UIFont.systemFont(ofSize:18)
        _regBtn.setTitle(label, for: .normal)
        _regBtn.backgroundColor = UIColor(hex: 0xf46363)
        _regBtn.layer.cornerRadius = 4
        _regBtn.layer.masksToBounds = true
        _regBtn.frame = CGRectMake(TextFieldLeftMargin, _passwordTextField.bottom + 25, TextFieldWidth, 50)
        _regBtn.addTarget(self, action: #selector(regBtnTapped), for: .touchUpInside)
        _topView.addSubview(_regBtn)
        
        
        //-------------用户协议
        let agreementView:UIView = UIView()
        _topView.addSubview(agreementView)
        
        let tipLabel2:UILabel = UILabel()
        tipLabel2.font = UIFont.systemFont(ofSize:12)
        tipLabel2.textColor = UIColor(hex: 0x2f3231)
        tipLabel2.text = "继续注册表示您已经同意"
        tipLabel2.sizeToFit()
        tipLabel2.frame = CGRectMake(0, 0, tipLabel2.width, tipLabel2.height)
        agreementView.addSubview(tipLabel2)
        
        let viewAgreementBtn:UIButton = UIButton(type:.system)
        viewAgreementBtn.titleLabel?.font = UIFont.systemFont(ofSize:12)
        viewAgreementBtn.setTitle("咿呀用户协议", for: .normal)
        viewAgreementBtn.setTitleColor(UIColor(hex: 0x2f3231), for: .normal)
        viewAgreementBtn.sizeToFit()
        viewAgreementBtn.frame = CGRectMake(tipLabel2.right, -6, viewAgreementBtn.width, viewAgreementBtn.height)
        viewAgreementBtn.addTarget(self, action: #selector(viewAgreementBtnTapped), for: .touchUpInside)
        agreementView.addSubview(viewAgreementBtn)
        
        //下划线
        let underline:UIView = UIView()
        underline.backgroundColor = UIColor(hex: 0x2f3231)
        underline.frame = CGRectMake(viewAgreementBtn.x, viewAgreementBtn.bottom - 6, viewAgreementBtn.width, 1)
        agreementView.addSubview(underline)
        
        agreementView.frame = CGRectMake(TextFieldLeftMargin, _regBtn.bottom + 18, viewAgreementBtn.right, tipLabel2.height)
        
        _topView.height = agreementView.bottom
    }
    
    private var getCodeButtonEnabled:Bool = false
    {
        didSet
        {
            if getCodeButtonEnabled != oldValue
            {
                let imageName:String = getCodeButtonEnabled ? "auth_btn_login" : "auth_img_bg_input"
                _getCodeBtn.setBackgroundImage(UIImage(named:imageName)?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 19, 0, 19), resizingMode: .stretch), for: .normal)
                if getCodeButtonEnabled
                {
                    _getCodeBtn.setTitle("获取验证码", for: .normal)
                }
            }
        }
    }
    
    //更新获取按钮上的文字
    private func updateGetCodeBtn()
    {
        //30秒内只能发送一次
        let time:Double = SW.Config.GetVerifyCodeCDTime - ((NSDate().timeIntervalSince1970 - _smsSendTime))
        
        if time > 1
        {
            _getCodeBtn.setTitle("\(Int(time))秒后获取", for: .normal)
            getCodeButtonEnabled = false
        }
        else
        {
            clearInterval(_intervalID)
            getCodeButtonEnabled = true
        }
        
    }
    
    //获取验证码按钮重置
    private func verifyCodeButtonReset()
    {
        _smsSendTime = 0
        clearInterval(_intervalID)
        _getCodeBtn.setTitle("获取验证码", for: .normal)
        getCodeButtonEnabled = true
    }
    
    //发送请求以获取验证码
    private func getVerifyCode(tel:String)
    {
        let askCheckCodeReq:SWVerifyCodeFetchReq = SWVerifyCodeFetchReq()
        askCheckCodeReq.phone = tel
        askCheckCodeReq.action = .Register
        askCheckCodeReq.successCallback = {response,cache in
            SVProgressHUD.showSuccess(withStatus:"验证码已发送")
        }
        
        askCheckCodeReq.failCallback = {[weak self] error in
            //验证码发送失败，需重新发送
            self?.verifyCodeButtonReset()
            SVProgressHUD.showError(withStatus:error.message)
        }
        load(askCheckCodeReq)
    }
    
    //注册
    private func register(phone:String, password:String, verify:String)
    {
        let req = SWRegisterReq()
        req.password = password
        req.phone = phone
        req.verifyCode = verify
        req.ssoTicket = ssoTicket
        req.successCallback = {[weak self] response,_ in
            if let registerRsp = response as? SWRegisterRsp,
                let data = registerRsp.data,
                let account = SWMainAccount(response: data)
            {
                self?._registered = true
                SWAccountManager.sharedManager().loginSuccess(account:account)
                
                let childrenCount:Int = account.children?.count ?? 0
                if childrenCount > 0
                {
                    SVProgressHUD.showSuccess(withStatus:"登陆成功")
                    SWMainApplication.sharedApplication.rootViewController?.showMainContent()
                }
                else
                {
                    //fetchInvitation()
                    SVProgressHUD.dismiss()
                    let viewController:SWChildInfoSupplementViewController = SWChildInfoSupplementViewController()
                    self?.navigationController?.pushViewController(viewController, animated: true)
                }
            }
            else
            {
                self?.registerFail(SWError.DefaultNetworkError)
            }
        }
        req.failCallback = {[weak self] error in
            self?.registerFail(error)
        }
        load(req)
    }
    
    private func registerFail(_ error:NSError)
    {
        _regBtn.isEnabled = true
        if error.code == SWErrorCode.VERIFY_CODE_Invalid
        {
            verifyCodeButtonReset()
        }
        SVProgressHUD.showError(withStatus:error.message)
    }
    
    //获取邀请信息
    private func fetchInvitation()
    {
        let req = SWInvitationFetchReq()
        req.successCallback = {[weak self] response,cache in
            if let invitationsRsp = (response as? SWInvitationFetchRsp)?.invitations
            {
                SVProgressHUD.dismiss()
                let invitations = invitationsRsp.flatMap({SWInvitation(invitation: $0)})
                if let invitation = invitations.valueAt(0)
                {
                    let viewController = SWInvitationHandleViewController(invitation: invitation)
                    viewController.forceSupplement = true
                    self?.navigationController?.pushViewController(viewController, animated: true)
                }
                else
                {
                    let viewController = SWChildAddViewController()
                    viewController.forceSupplement = true
                    self?.navigationController?.pushViewController(viewController, animated: true)
                }
            }
            else
            {
                self?.fetchInvitationFail(SWError.DataError)
            }
        }
        req.failCallback = {[weak self] error in
            self?.fetchInvitationFail(error)
        }
        load(req)
    }
    
    private var _fetchInvitationFailTimes:Int = 0
    private func fetchInvitationFail(_ error:NSError)
    {
        //失败次数超过3次，当做没有邀请信息，转到孩子添加页
        _fetchInvitationFailTimes += 1
        if _fetchInvitationFailTimes >= 3
        {
            let viewController = SWChildAddViewController()
            viewController.forceSupplement = true
            navigationController?.pushViewController(viewController, animated: true)
        }
        else
        {
            SVProgressHUD.showError(withStatus:"注册失败，稍后重试")
        }
    }
    
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
    {
        var inputEnable:Bool = true
        if textField == _telTextField
        {
            //手机号限制只能输入20个以内的数字
            let MaxCount:Int = 20
            inputEnable = string == "" || ((textField.text?.length ?? 0) + string.length < MaxCount && Regex("^[\\d-]+$").test(string))
        }
        return inputEnable
    }
    
//    func textFieldDidBeginEditing(textField: UITextField)
//    {
//        UIView.animate(withDuration:0.3, animations: {
//            self._topView.y = 0
//        })
//    }
    
    //MARK ============================================================================================
    //==============================               Selector             ===============================
    //=================================================================================================
    
    
    @objc private func getCodeBtnTapped()
    {
        let tel:String = _telTextField.text ?? ""
        if tel == ""
        {
            SVProgressHUD.showError(withStatus:"输入手机号码")
            return
        }
        if inWaiting
        {
            return
        }
        _smsSendTime = NSDate().timeIntervalSince1970
        
        getVerifyCode(tel: tel)
        clearTimeout(self._intervalID)
        _intervalID = setInterval(1, closure: {
            
            self.updateGetCodeBtn()
            
        })
        updateGetCodeBtn()
    }
    
    @objc private func viewAgreementBtnTapped()
    {
        if let url = Bundle.main.url(forResource: "protocol", withExtension: "html"),
           let webViewController = SVModalWebViewController(url: url)
        {
            present(webViewController, animated: true, completion: nil)
        }
    }
    
    @objc private func regBtnTapped()
    {
        guard let tel = _telTextField.text , tel != "" else
        {
            SVProgressHUD.showError(withStatus:"输入手机号码")
            return
        }
        guard let code = _codeTextField.text , code != "" else
        {
            SVProgressHUD.showError(withStatus:"输入验证码")
            return
        }
        guard let password1 = _passwordTextField.text , password1 != "" else
        {
            SVProgressHUD.showError(withStatus:"输入密码")
            return
        }
        if password1.length < 6
        {
            SVProgressHUD.showError(withStatus:"密码不能少于6位数")
            return
        }
        
        if _registered
        {
            fetchInvitation()
        }
        else
        {
            register(phone: tel, password:password1, verify:code)
        }
        
        SVProgressHUD.show(withStatus:"注册中...")
        _regBtn.isEnabled = false
    }
    
    //点击空白区域，内容下移
    @objc private func viewTapped()
    {
        view.endEditing(true)
//        UIView.animate(withDuration:0.3, animations: {
//            self._topView.center = self.view.center
//        })
    }


}
